var express = require('express')

var Student = require('./student')

var fs = require('fs')

var router = express.Router()

router.get('/students', function(req, res){
	Student.find().then((data)=>{
		res.render('index.html',{
			title:'学生管理系统',
			fruits:['菠萝蜜', '牛油果', '哈密瓜', '葡萄'],
			students:data
		})
	},(err)=>res.status(500).send('server error.'))
})

router.get('/students/new', function(req, res){
	res.render('new.html', {
		title:'新增学生信息'
	})
})

router.post('/students/new', function(req, res){
	new Student(req.body).save().then(()=>res.redirect('/students'), (err)=>res.status(500).send('server error.'))
})

router.get('/students/edit', function(req, res){
	Student.findById(req.query.id)
		.then((student)=>{
			res.render('edit.html',{
				title:'编辑学生信息',
				student:student
			})
		},(err)=>res.status(500).send('server error.'))
})

router.post('/students/edit', function(req, res){
	Student.findByIdAndUpdate(req.body.id, req.body)
		.then(()=>res.redirect('/students'), (err)=>res.status(500).send('server error.'))
})

router.get('/students/delete', function(req, res){
	Student.findByIdAndRemove(req.query.id)
		.then(()=>res.redirect('/students'),(err)=>res.status(5000).send('server error.'))
})

module.exports = router